# -*- coding: utf-8 -*-
# @Time : 2021-01-12 22:02
# @Author : derek.zhang
# @File : upload_views.py
# @Software: PyCharm
import errno
import json
import os
import shutil
import string
import time
from random import random
from sys import platform

from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext
from django.urls import reverse, reverse_lazy
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import FormView

from deploy.forms import UploadFileForm
from deploy.models import DeployPool, DeployStatus
from manabe import settings


def render_to_json_response(context, **response_kwargs):
    data = json.dumps(context)
    response_kwargs['content_type'] = 'application/json'
    return HttpResponse(data, **response_kwargs)

class DeployVersionUploadView(FormView):
    template_name = 'deploy/upload_deploversion.html'
    form_class = UploadFileForm

    def form_invalid(self, form):
        return self.render_to_response(RequestContext(self.request, {'form':form}))

    def form_valid(self, form):
        current_user = self.request.user
        random_letter = ''.join(random.sample(string.ascii_letters,2))
        deploy_version = time.strftime('%Y-%m%d-%H%M%s',time.localtime()) + random_letter.upper()
        description = form.cleaned_data['description']
        app_name = form.cleaned_data['app_name']
        is_inc_tot = form.cleaned_data['is_inc_tot']
        deploy_type = form.cleaned_data['deploy_type']
        file_path = form.cleaned_data['file_pathy']
        deployversion_upload_deone(app_name, deploy_version, file_path)
        nginx_base_url = settings.NGINX_URL
        nginx_url = '{}/{}/{}'.format(nginx_base_url, app_name, deploy_version)

        DeployPool.objects.create(
            name = deploy_version,
            app_name = app_name,
            branch_build= 'upload',
            is_inc_tot= is_inc_tot,
            deploy_type=  deploy_type,
            create_user= current_user,
            nginx_url = nginx_url,
            description= description,
            deploy_status=DeployStatus.objects.get(name='BUILD')
        )
        return HttpResponseRedirect(reverse('deploy:list'))

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['current_page_name'] = '仙剑发布单(上传)'
        return context

    def get_success_url(self):
        # form 成功验证时将表单重定向到
        # 都是将别名转化成url
        return reverse_lazy('version:deployversion-list')


@csrf_exempt
def fileupload(request):
    files = request.FILES.getlist('files[]')
    file_name_list = []
    for f in files:
        if platform.system() == 'Windows':
            destination = 'c://tmp//'
        elif platform.system() == 'Linux':
            destination = '/tmp/'
        else:
            destination = '/tmp/'
        if not os.path.exists(destination):
            # 创建递归的目录树, 可以是相对路径或者绝对路径
            os.makedirs(destination)
        with open(destination+f.name, 'wb+') as destination:
            for chunk in f.chunks(chunk_size = 10000):
                destination.write(chunk)
        file_name_list.append(f.name)
    return render_to_json_response(''.join(file_name_list))

def deployversion_upload_deone(app_name, deploy_version, upload_file):
    if platform.system() == 'Windows':
        src_file = 'c://tmp//' + upload_file
        dest_floder = 'c://nfsc'
    elif platform.system() == 'Linux':
        src_file = '/tmp/' + upload_file
        dest_floder = '/nfsc/{}/{}'.format(app_name, deploy_version)

    mkdir_p(dest_floder)
    dest_file = dest_floder + upload_file
    shutil.move(src_file, dest_file)


def mkdir_p(path):
    try:
        os.mkdirs(path)
    except OSError as exc:
        if exc.errno == errno.EEXIST and os.path.isdir(path):
            path
        else:
            raise OSError
